package com.gc.server.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.gc.server.common.Const;
import com.gc.server.dao.*;
import com.gc.server.entity.*;
import com.gc.server.enums.UserVipEnum;
import com.gc.server.service.PointTypeService;
import com.gc.server.vo.ImgOrderStatusEnum;
import com.gc.server.vo.ImgOrderVo;
import com.gc.server.vo.UserScore;
import com.gc.server.vo.down.ImgOrderDown;
import com.gc.server.vo.down.ImgOrderItemDown;
import com.gc.server.vo.down.TodoDown;
import com.yf.response.RRException;
import com.yf.tz.service.AccountRecordService;
import com.yf.tz.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import com.gc.server.service.ImgOrderService;
import com.yf.service.impl.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;

/**
 * 线下报单Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Thu Mar 12 15:17:51 CST 2020
 */
@Service
public class ImgOrderServiceImpl extends BaseServiceImpl<ImgOrderEntity> implements ImgOrderService {

    private ImgOrderDao imgOrderDao;


    @Autowired
    public void setDao(ImgOrderDao imgOrderDao) {
        this.imgOrderDao = imgOrderDao;
        super.setBaseDao(imgOrderDao);
    }


    @Override
    public List<ImgOrderVo> queryListVo(ImgOrderVo imgOrderVo) {
        return imgOrderDao.queryListVo(imgOrderVo);
    }

    @Override
    public ImgOrderVo getVo(Long id) {
        return imgOrderDao.getVo(id);
    }


    /**内部方法**/


    /**
     * 外部方法实现
     **/

    @Autowired
    private UserDao userDao;


    String getTopInfo(Long userId) {
        UserEntity user = userDao.get(userId);
        StringBuilder sb = new StringBuilder();
        Integer index = 0;
        while (user.getPid() != Const.ADMIN_ID) {
            user  = userDao.get(user.getPid());
            sb.append(user.getCode()).append(user.getName()).append("_");
            index++;
            if(index>30){
                throw new RRException("层级死循环:ID"+userId);
            }
        }
        return sb.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ImgOrderEntity commit(Long userId, String img, String mobile, Long cusId, String remark, BigDecimal point, BigDecimal money, Long pointType, Long[] ids, Integer[] numbers) {
        //只做提交 审核后才给钱
        ImgOrderEntity orderEntity = new ImgOrderEntity(img, mobile, userId, new Date(), ImgOrderStatusEnum.WAIT.getIndex(), cusId, pointType, remark,getTopInfo(userId));
        imgOrderDao.save(orderEntity);
        buildOrderItem(orderEntity, numbers, ids);
//        orderEntity.setPoint(point);
//        if(pointType==2){//晒单且会VIP 才会有兑费
//            //晒单不需要审核直接先送
//            PointTypeEntity typeEntity = pointTypeService.get(pointType);
//            if(typeEntity!=null){
//                accountService.rewardPoint(userId,point,"晒单直接赠送",null);
//            }
//            //如果需要兑费
//            if(money.compareTo(BigDecimal.ZERO)>0&&UserVipEnum.YES.getIndex() == userEntity.getVip()){
//                orderEntity.setMoney(money);
//            }else { //直接通过
//                orderEntity.setMoney(BigDecimal.ZERO);
//                orderEntity.setStatus(ImgOrderStatusEnum.PASS.getIndex());
//            }
//        }else {
//            orderEntity.setMoney(BigDecimal.ZERO);
//        }

        return orderEntity;
    }


    @Autowired
    private LinkGoodsDao goodsDao;

    @Autowired
    private ImgOrderItemDao itemDao;

    List<ImgOrderItemEntity> buildOrderItem(ImgOrderEntity order, Integer[] numbers, Long[] ids) {
        if(numbers==null||ids==null){
            throw new RRException("请填写产品!");
        }
        BigDecimal sumPoint = BigDecimal.ZERO;
        BigDecimal sumMoney = BigDecimal.ZERO;
        BigDecimal sumPrice = BigDecimal.ZERO;
        List<ImgOrderItemEntity> items = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ids.length; i++) {
            if (i >= numbers.length) {
                break;
            }
            LinkGoodsEntity goods = goodsDao.get(ids[i]);
            ImgOrderItemEntity item = new ImgOrderItemEntity(order.getId(), ids[i], goods.getPoint(), goods.getMoney(), goods.getName(), numbers[i]);
            sumPrice = goods.getPrice().multiply(new BigDecimal((numbers[i])));
            sumPoint = sumPoint.add(goods.getPoint().multiply(new BigDecimal(numbers[i])));
            sumMoney = sumMoney.add(goods.getMoney().multiply(new BigDecimal(numbers[i])));
            sb.append(item.getGoodsName()).append("X").append(item.getQuantity());
            items.add(item);
            itemDao.save(item);
        }
        UserEntity userEntity = userDao.get(order.getUserId());
        //只有VIP才有兑费
        if (UserVipEnum.YES.getIndex() != userEntity.getVip()) {
            sumMoney = BigDecimal.ZERO;
        }
        order.setMoney(sumMoney);
        order.setPrice(sumPrice);
        order.setPoint(sumPoint);
        order.setRemark(sb.toString());
        update(order);
        return items;
    }


    @Autowired
    private PointTypeService pointTypeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ImgOrderEntity pass(Long userId, Long orderId) {
        ImgOrderEntity orderEntity = imgOrderDao.get(orderId);
        if (!orderEntity.getStatus().equals(ImgOrderStatusEnum.WAIT.getIndex())) {
            throw new RRException("请勿重复审核");
        }
        //有兑费 晒单才有兑费 业务员审核
        if (orderEntity.getMoney().compareTo(BigDecimal.ZERO) > 0) {
            accountService.rewardPoint(orderEntity.getUserId(), orderEntity.getMoney(), "晒单兑费奖励", null);
        } else { //没有兑费 直接审核 药店审核
            PointTypeEntity typeEntity = pointTypeService.get(orderEntity.getTypeId());
            if (typeEntity != null) {
                accountService.rewardPoint(orderEntity.getUserId(), typeEntity.getPoint(), typeEntity.getName() + "赠送", null);
            }
        }
        //设置通过
        orderEntity.setAdminId(userId);
        UserEntity userEntity = userDao.get(userId);
        orderEntity.setAdminName(userEntity.getName());
        orderEntity.setStatus(ImgOrderStatusEnum.PASS.getIndex());
        imgOrderDao.update(orderEntity);
        return orderEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ImgOrderEntity refuse(Long userId, Long orderId) {
        ImgOrderEntity orderEntity = imgOrderDao.get(orderId);
        if (!orderEntity.getStatus().equals(ImgOrderStatusEnum.WAIT.getIndex())) {
            throw new RRException("请勿重复审核");
        }
        orderEntity.setAdminId(userId);
        UserEntity userEntity = userDao.get(userId);
        orderEntity.setAdminName(userEntity.getName());
        orderEntity.setStatus(ImgOrderStatusEnum.REFUSE.getIndex());
        imgOrderDao.update(orderEntity);
        return orderEntity;
    }


    @Autowired
    private AccountService accountService;

    @Override
    public List<ImgOrderVo> listByTop(Long userId) {
        return imgOrderDao.listByTop(userId);
    }

    @Override
    public List<ImgOrderVo> listByUserId(Long userId) {
        return imgOrderDao.listByUserId(userId);
    }

    @Override
    public ImgOrderEntity bind(Long userId, String mobile, Long orderId) {
        ImgOrderEntity imgOrder = get(orderId);
        if (imgOrder.getCusId() != null) {
            throw new RRException("已经绑定!");
        }
        //直接绑定用户的手机号
        UserEntity userEntity = userDao.get(userId);
        imgOrder.setMobile(userEntity.getMobile());
        imgOrder.setCusId(userId);
        update(imgOrder);
        return imgOrder;
    }

    @Override
    public List<ImgOrderItemEntity> findItems(Long id) {
        return imgOrderDao.findItems(id);
    }

    @Override
    public ImgOrderEntity check(ImgOrderEntity order) {
        //查找数据库状态
        ImgOrderEntity imgOrder = imgOrderDao.get(order.getId());
        boolean flag = false;
        if(ImgOrderStatusEnum.PASS.getIndex()!=imgOrder.getStatus()){
            flag = true;
        }
        //移除所有组件
        imgOrderDao.deleteItems(order.getId());
        Integer[] numbers = new Integer[order.getItems().size()];
        Long[] ids = new Long[order.getItems().size()];
        for (int i = 0; i < order.getItems().size(); i++) {
            ImgOrderItemEntity item = order.getItems().get(i);
            if (item.getGoodsId() != null && item.getQuantity() != null) {
                numbers[i] = item.getQuantity();
                ids[i] = item.getGoodsId();
            }
        }
        buildOrderItem(order, numbers, ids);
        update(order);
        //通过的话转钱
        if (flag&&order.getStatus().equals(ImgOrderStatusEnum.PASS.getIndex())&&order.getPoint()!=null&&order.getMoney()!=null) {
            accountService.rewardPoint(order.getUserId(), order.getPoint().add(order.getMoney()), "晒单奖励", String.valueOf(order.getId()));
        }
        return order;
    }

    @Override
    public void downLoad(HttpServletResponse response, List<ImgOrderVo> list) {
        try {

            List<ImgOrderItemDown> downs = sumItem(list);
            List<ImgOrderDown> datas = list.stream().filter(vo -> vo.getUser()!=null).map(item -> new ImgOrderDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "记录").head(ImgOrderDown.class).build();
            excelWriter.write(datas, writeSheet);
            //统计
            writeSheet = EasyExcel.writerSheet(1, "汇总").head(ImgOrderItemDown.class).build();
            excelWriter.write(downs, writeSheet);
            excelWriter.finish();
//            EasyExcel.write(response.getOutputStream(), TodoDown.class).sheet("模板" ).doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    List<ImgOrderItemDown> sumItem(List<ImgOrderVo> list) {
        Map<String, ImgOrderItemDown> sum = new HashMap<>();
        for (ImgOrderVo orderVo : list) {
            List<ImgOrderItemEntity> items = imgOrderDao.findItems(orderVo.getImgOrder().getId());
            Integer quantity = 0;
            for (ImgOrderItemEntity item : items) {
                if(orderVo.getUser()==null)continue;
                String key = orderVo.getUser().getId() + "_" + item.getGoodsId();
                ImgOrderItemDown itemDown = new ImgOrderItemDown(orderVo,item);
                itemDown.setShopName(orderVo.getUser().getShopName());
                if (sum.containsKey(key)) {
                    itemDown = sum.get(key);
                }
                quantity+=item.getQuantity();
                itemDown.add(item.getQuantity());
                sum.put(key, itemDown);
            }
            orderVo.getImgOrder().setQuantity(quantity);
        }
        return sum.values().stream().collect(Collectors.toList());
    }
}
